<?php
class Agitum_Controller_Plugin_Navigation extends Zend_Controller_Plugin_Abstract
{
	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
//        printf( "Class: %s; Method: %s, File: %s; Line: %s<br/>\n", __CLASS__, __FUNCTION__, __FILE__, __LINE__);

		$auth = Zend_Auth::getInstance();
		$role = ($auth->hasIdentity()) ? $auth->getIdentity()->role : 'guest';

		$slot = new Agitum_Model_Cache_Slot_Page_Tree();
        $pages = $slot->load();
        if ( !$pages ) {
        	$obj = new Agitum_Model_Page();
        	$pages = $obj->getContainer();
        	foreach ( $pages as $i => $row ) {
        		$slot->addTag( new Agitum_Model_Cache_Tag_Page($row['id']) );
        	}
        	$slot->addTag( new Agitum_Model_Cache_Tag_Page_Tree() );
        	$slot->save($pages);
        }
        
		$container = new Zend_Navigation($pages);   
		Zend_Registry::set('Zend_Navigation', $container);
		
		$front = Zend_Controller_Front::getInstance();
		$router = $front->getRouter();
		
		$view = Zend_Registry::get('Zend_View');
		$view->navigation($container);
		
		try {
		    $view->current_route = $router->getCurrentRouteName();
		} catch (Exception $e) {}
		

		$acl = Zend_Registry::get('Zend_Acl');
		Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($acl);
		Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole((string)$role);
		
	}
}
